package com.example.wechathook.hook;

import static de.robv.android.xposed.XposedBridge.hookAllMethods;
import static de.robv.android.xposed.XposedBridge.hookMethod;
import static de.robv.android.xposed.XposedHelpers.callMethod;
import static de.robv.android.xposed.XposedHelpers.findAndHookMethod;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.location.Criteria;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.SystemClock;
import android.telephony.CellLocation;

import com.example.wechathook.util.PreferenceUtils;

import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage;

public class LocationHook2 extends BaseHook {

	private ClassLoader classLoader;
	private boolean open;
	private double lat;
	private double lon;

	@Override
	public void hook(XC_LoadPackage.LoadPackageParam lpp) {

		classLoader = lpp.classLoader;
		open = PreferenceUtils.locationSwtich();
		lat = Double.parseDouble(PreferenceUtils.lat());
		lon = Double.parseDouble(PreferenceUtils.lon());

		if (!open) {
			return;
		}

		findAndHookMethod(WifiManager.class.getCanonicalName(), classLoader, "getScanResults", new XC_MethodHook() {
			@Override
			protected void afterHookedMethod(MethodHookParam param) throws Throwable {
				param.setResult(null);
			}
		});

		findAndHookMethod("android.telephony.TelephonyManager", classLoader, "getCellLocation", new XC_MethodHook() {
			@Override
			protected void afterHookedMethod(MethodHookParam param) throws Throwable {
				param.setResult(null);
			}
		});

		findAndHookMethod("android.telephony.PhoneStateListener", classLoader, "onCellLocationChanged",
				CellLocation.class, new XC_MethodHook() {
					@Override
					protected void afterHookedMethod(MethodHookParam param) throws Throwable {
						param.setResult(null);
					}
				});

		if (Build.VERSION.SDK_INT > 22) {
			findAndHookMethod("android.telephony.TelephonyManager", classLoader, "getPhoneCount", new XC_MethodHook() {
				@Override
				protected void afterHookedMethod(MethodHookParam param) throws Throwable {
					param.setResult(1);
				}
			});
		}

		if (Build.VERSION.SDK_INT < 23) {
			findAndHookMethod("android.telephony.TelephonyManager", classLoader, "getNeighboringCellInfo",
					new XC_MethodHook() {
						@Override
						protected void afterHookedMethod(MethodHookParam param) throws Throwable {
							param.setResult(new ArrayList<>());
						}
					});
		}

		if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
			findAndHookMethod("android.telephony.TelephonyManager", classLoader, "getAllCellInfo", new XC_MethodHook() {
				@Override
				protected void afterHookedMethod(MethodHookParam param) throws Throwable {
					param.setResult(null);
				}
			});
			findAndHookMethod("android.telephony.PhoneStateListener", classLoader, "onCellInfoChanged", List.class,
					new XC_MethodHook() {
						@Override
						protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
							param.setResult(null);
						}
					});
		}

		findAndHookMethod(LocationManager.class, "getLastKnownLocation", new XC_MethodHook() {
			@Override
			protected void afterHookedMethod(MethodHookParam param) throws Throwable {
				Location l = new Location(LocationManager.GPS_PROVIDER);
				l.setLatitude(lat);
				l.setLongitude(lon);

				l.setAccuracy(100f);
				l.setTime(System.currentTimeMillis());
				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
					l.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
				}
				param.setResult(l);
			}
		});

		findAndHookMethod("android.net.NetworkInfo", classLoader, "getTypeName", new XC_MethodHook() {
			@Override
			protected void afterHookedMethod(MethodHookParam param) throws Throwable {
				param.setResult("WIFI");
			}
		});
		findAndHookMethod("android.net.NetworkInfo", classLoader, "isConnectedOrConnecting", new XC_MethodHook() {
			@Override
			protected void afterHookedMethod(MethodHookParam param) throws Throwable {
				param.setResult(true);
			}
		});

		findAndHookMethod("android.net.NetworkInfo", classLoader, "isConnected", new XC_MethodHook() {
			@Override
			protected void afterHookedMethod(MethodHookParam param) throws Throwable {
				param.setResult(true);
			}
		});

		findAndHookMethod("android.net.NetworkInfo", classLoader, "isAvailable", new XC_MethodHook() {
			@Override
			protected void afterHookedMethod(MethodHookParam param) throws Throwable {
				param.setResult(true);
			}
		});

		findAndHookMethod("android.telephony.CellInfo", classLoader, "isRegistered", new XC_MethodHook() {
			@Override
			protected void afterHookedMethod(MethodHookParam param) throws Throwable {
				param.setResult(true);
			}
		});

		hookAllMethods(LocationManager.class, "getProviders", new XC_MethodHook() {
			@Override
			protected void afterHookedMethod(MethodHookParam param) throws Throwable {
				ArrayList<String> arrayList = new ArrayList<>();
				arrayList.add("gps");
				param.setResult(arrayList);
			}
		});

		findAndHookMethod(LocationManager.class, "getBestProvider", Criteria.class, Boolean.TYPE, new XC_MethodHook() {
			@Override
			protected void afterHookedMethod(MethodHookParam param) throws Throwable {
				param.setResult("gps");
			}
		});

		findAndHookMethod("android.location.LocationManager", classLoader, "getGpsStatus", GpsStatus.class,
				new XC_MethodHook() {
					@Override
					protected void afterHookedMethod(MethodHookParam param) throws Throwable {
						GpsStatus gss = (GpsStatus) param.getResult();
						if (gss == null)
							return;

						Class<?> clazz = GpsStatus.class;
						Method m = null;
						for (Method method : clazz.getDeclaredMethods()) {
							if (method.getName().equals("setStatus")) {
								if (method.getParameterTypes().length > 1) {
									m = method;
									break;
								}
							}
						}
						if (m == null)
							return;

						// access the private setStatus function of GpsStatus
						m.setAccessible(true);

						// make the apps belive GPS works fine now
						int svCount = 5;
						int[] prns = { 1, 2, 3, 4, 5 };
						float[] snrs = { 0, 0, 0, 0, 0 };
						float[] elevations = { 0, 0, 0, 0, 0 };
						float[] azimuths = { 0, 0, 0, 0, 0 };
						int ephemerisMask = 0x1f;
						int almanacMask = 0x1f;

						// 5 satellites are fixed
						int usedInFixMask = 0x1f;

						XposedHelpers.callMethod(gss, "setStatus", svCount, prns, snrs, elevations, azimuths,
								ephemerisMask, almanacMask, usedInFixMask);
						param.args[0] = gss;
						param.setResult(gss);
						try {
							m.invoke(gss, svCount, prns, snrs, elevations, azimuths, ephemerisMask, almanacMask,
									usedInFixMask);
							param.setResult(gss);
						} catch (Exception e) {
							XposedBridge.log(e);
						}
					}
				});

		for (Method method : LocationManager.class.getDeclaredMethods()) {
			if (method.getName().equals("requestLocationUpdates") && !Modifier.isAbstract(method.getModifiers())
					&& Modifier.isPublic(method.getModifiers())) {
				XposedBridge.hookMethod(method, new XC_MethodHook() {
					@Override
					protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
						if (param.args.length >= 4 && (param.args[3] instanceof LocationListener)) {

							LocationListener ll = (LocationListener) param.args[3];

							Class<?> clazz = LocationListener.class;
							Method m = null;
							for (Method method : clazz.getDeclaredMethods()) {
								if (method.getName().equals("onLocationChanged")
										&& !Modifier.isAbstract(method.getModifiers())) {
									m = method;
									break;
								}
							}

							Location l = new Location(LocationManager.GPS_PROVIDER);
							l.setLatitude(lat);
							l.setLongitude(lon);
							l.setAccuracy(10.00f);
							l.setTime(System.currentTimeMillis());
							if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
								l.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
							}
							callMethod(ll, "onLocationChanged", l);
							try {
								if (m != null) {
									m.invoke(ll, l);
								}
							} catch (Exception e) {
								XposedBridge.log(e);
							}
						}
					}
				});
			}

			if (method.getName().equals("requestSingleUpdate ") && !Modifier.isAbstract(method.getModifiers())
					&& Modifier.isPublic(method.getModifiers())) {
				hookMethod(method, new XC_MethodHook() {
					@Override
					protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
						if (param.args.length >= 3 && (param.args[1] instanceof LocationListener)) {

							LocationListener ll = (LocationListener) param.args[3];

							Class<?> clazz = LocationListener.class;
							Method m = null;
							for (Method method : clazz.getDeclaredMethods()) {
								if (method.getName().equals("onLocationChanged")
										&& !Modifier.isAbstract(method.getModifiers())) {
									m = method;
									break;
								}
							}

							try {
								if (m != null) {
									Location l = new Location(LocationManager.GPS_PROVIDER);
									l.setLatitude(lat);
									l.setLongitude(lon);
									l.setAccuracy(100f);
									l.setTime(System.currentTimeMillis());
									if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
										l.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
									}
									m.invoke(ll, l);
								}
							} catch (Exception e) {
								XposedBridge.log(e);
							}
						}
					}
				});
			}
		}
	}

}
